﻿//-----------------------------------------------------------------------
// <copyright file="HttpRequestHelper.cs" company="lctc Enterprises">
//      Copyright (c) lctc Enterprises. All rights reserved.
// </copyright>
// <date>2016-5-20 13:29:31</date>
// <Author>zhoujunping</Author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Mall.Common
{
    public class HttpHeaderHelper
    {
        /// <summary>
        /// Gets or sets contentType
        /// </summary>
        public static string ContentType { get { return "application/x-www-form-urlencoded"; } }

        /// <summary>
        ///  Gets or sets accept
        /// </summary>
        public static string Accept { get { return "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8"; } }

        /// <summary>
        /// Gets or sets userAgent
        /// </summary>
        public static string UserAgent { get { return "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0"; } }

        /// <summary>
        /// Gets or sets maxTry
        /// </summary>
        public static int MaxTry { get { return 2000; } }
    }

    /// <summary>
    /// 请求头
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="getUrl">getUrl</param>
        /// <param name="cookieContainer">cookieContainer</param>
        /// <returns>string</returns>
        public static string Get(string getUrl, string charset = "utf-8")
        {
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                httpWebRequest.ContentType = HttpHeaderHelper.ContentType;
                httpWebRequest.ServicePoint.ConnectionLimit = HttpHeaderHelper.MaxTry;
                httpWebRequest.Referer = getUrl;
                httpWebRequest.Accept = HttpHeaderHelper.Accept;
                httpWebRequest.UserAgent = HttpHeaderHelper.UserAgent;
                httpWebRequest.Method = "GET";
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(charset));
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
                return html;
            }
            catch (Exception e)
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }

                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }

                throw e;
            }
        }

        /// <summary>
        /// 获取html
        /// </summary>
        /// <param name="getUrl">getUrl</param>
        /// <param name="post">post</param>
        /// <param name="cookieContainer">cookieContainer</param>
        /// <returns>string</returns>
        public static string Post(string getUrl, string post, string charset = "utf-8")
        {
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
                httpWebRequest.ContentType = HttpHeaderHelper.ContentType + ";" + charset;
                httpWebRequest.ServicePoint.ConnectionLimit = HttpHeaderHelper.MaxTry;
                //httpWebRequest.Referer = getUrl;
                httpWebRequest.Accept = HttpHeaderHelper.Accept;
                httpWebRequest.UserAgent = HttpHeaderHelper.UserAgent;
                httpWebRequest.Method = "POST";

                byte[] postdatabyte = Encoding.GetEncoding(charset).GetBytes(post);
                httpWebRequest.ContentLength = postdatabyte.Length;
                httpWebRequest.AllowAutoRedirect = false;
                httpWebRequest.Timeout = 60000;
                httpWebRequest.ReadWriteTimeout = 60000;
                httpWebRequest.KeepAlive = false;

                httpWebRequest.ProtocolVersion = HttpVersion.Version10;

                ////提交请求
                Stream stream;
                stream = httpWebRequest.GetRequestStream();
                stream.Write(postdatabyte, 0, postdatabyte.Length);
                stream.Close();

                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                //responseStream.WriteTimeout = 60000;
                //StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(charset));
                //string html = streamReader.ReadToEnd();LogBLL.info("debug1");
                MemoryStream memoryStream = new MemoryStream();
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    memoryStream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                string html = Encoding.UTF8.GetString(memoryStream.ToArray());

                memoryStream.Close();
                //streamReader.Close();
                responseStream.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();

                return html;
            }
            catch (Exception e)
            {
                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }

                if (httpWebResponse != null)
                {
                    httpWebResponse.Close();
                }

                throw e;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">抓取url</param>
        /// <param name="savePath">保存地址</param>
        /// <returns></returns>
        public static void HttpDown(string url, string savePath)
        {
            try
            {
                HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;

                req.ContentType = "application/octet-stream";

                HttpWebResponse response = req.GetResponse() as HttpWebResponse;

                Stream stream = response.GetResponseStream();

                FileInfo file = new FileInfo(savePath);

                DirectoryInfo dir = new DirectoryInfo(file.DirectoryName);

                //删除原有目录
                if (!dir.Exists)
                {
                    dir.Create();
                }


                FileStream fs = File.Create(savePath);

                long length = response.ContentLength;


                int i = 0;
                do
                {
                    byte[] buffer = new byte[1024];

                    i = stream.Read(buffer, 0, 1024);

                    fs.Write(buffer, 0, i);

                } while (i > 0);


                fs.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
